package com.wzu.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wzu.entity.Result;
import com.wzu.entity.User;
import com.wzu.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/users")
@CrossOrigin
public class UserController {
    @Autowired
    private UserService service;

    // 查询所有用户
    @GetMapping("/list")
    public Result getAllUsers() {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        return new Result("查询成功", service.list(queryWrapper), 200);
    }

    // 按名称搜索用户
    @GetMapping("/search")
    public Result searchUsers(@RequestParam(required = false) String fullname) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        if (fullname != null && !fullname.isEmpty()) {
            queryWrapper.like("fullname", fullname);
        }
        return new Result("查询成功", service.list(queryWrapper), 200);
    }

    // 用户登录
    @PostMapping("/login")
    public Result login(@RequestBody User user) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userid", user.getUserid())
                   .eq("password", user.getPassword());
        User result = service.getOne(queryWrapper);
        if (result != null) {
            return new Result("登录成功", result, 200);
        } else {
            return new Result("登录失败", null, 404);
        }
    }

    // 添加用户
    @PostMapping("/add")
    public Result addUser(@RequestBody User user) {
        if (service.addUser(user)) {
            return new Result("添加成功", null, 200);
        } else {
            return new Result("用户账号已存在", null, 400);
        }
    }

    // 更新用户信息
    @PutMapping("/update")
    public Result updateUser(@RequestBody User user) {
        if (service.updateUser(user)) {
            return new Result("更新成功", null, 200);
        } else {
            return new Result("用户账号已存在或更新失败", null, 400);
        }
    }

    // 删除用户
    @DeleteMapping("/delete/{id}")
    public Result deleteUser(@PathVariable Integer id) {
        if (service.deleteUser(id)) {
            return new Result("删除成功", null, 200);
        } else {
            return new Result("删除失败", null, 400);
        }
    }
}
